<?php

namespace Aiweline\AiReviewForMagentoProduct\Lib\Magento;

use GuzzleHttp\Client;
use Weline\Framework\Cache\CacheFactory;
use Weline\Framework\Cache\CacheInterface;
use Weline\Framework\Manager\ObjectManager;

class AdminToken
{

    static function token()
    {
        if (Config::$admin_token) {
            return Config::$admin_token;
        }
        /** @var CacheInterface $cache */
        $cache = ObjectManager::getInstance(CacheFactory::class);
        $adminToken = $cache->get('admin_token');
        if ($adminToken) {
            Config::$admin_token = $adminToken;
            return Config::$admin_token;
        }
        $apiUrl = Config::api('integration/admin/token');
        $client = new Client();
        $response = $client->request('post', $apiUrl, [
            'json' => [
                'username' => Config::get('username'),
                'password' => Config::get('password'),
            ],
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'verify' => false, // 去掉ssl验证
        ]);
        if ($response->getStatusCode() !== 200) {
            // 打印响应体 body 和响应头
            dd($response);
            return;
        }
        $responseData = json_decode($response->getBody()->getContents(), true);
        Config::$admin_token = $responseData;
        $cache->set('admin_token', $responseData, 3600);
        return Config::$admin_token;
    }
}